import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import "./index.less";
import memoryUtils from "../../utils/memoryUtils";
import storageUtils from "../../utils/storageUtils";
import { formateDate } from "../../utils/dateUtils";
import { reqWeather } from "../../api/index";
import menuList from "../../config/menuConfig";
import { Modal } from "antd";
import LinkButton from "../link-button/index";

class Header extends Component {
  state = {
    currentTime: formateDate(Date.now()), //当前时间
    dayPictureUrl: "", //天气图片url
    weather: "", // 天气的文本
  };

  //  开启定时器更新时间
  getTime = () => {
    //   每个一秒获取当前时间
    this.timer = setInterval(() => {
      const currentTime = formateDate(Date.now());
      this.setState({ currentTime });
    }, 1000);
  };
  // 获取当前天气
  getWeather = async () => {
    //   调用接口异步获取数据
    const { dayPictureUrl, weather } = await reqWeather("北京");
    this.setState({
      dayPictureUrl,
      weather,
    });
  };
  // 获取当前导航,改变面包屑导航
  getTitle = () => {
    //   记得Header不是路由组件,所以withRouter
    const curPath = this.props.location.pathname;
    let title;
    menuList.forEach((item) => {
      if (item.key === curPath) {
        title = item.title;
      } else if (item.children) {
        // 在子路由中查找匹配的title
        const cItem = item.children.find((cItem) => {
          return cItem.key === curPath;
        });
        if (cItem) {
          title = cItem.title;
        }
      }
    });
    return title;
  };

  //   组件卸载之前,清除定时器
  componentWillUnmount() {
    clearInterval(this.timer);
  }

  //   退出登录
  logoOut = () => {
    Modal.confirm({
      content: "确认退出吗?",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        // 删除用户信息  内存和本地的都删除
        memoryUtils.user = {};
        storageUtils.removeUser();
        // 跳转到登录
        this.props.history.replace("/login"); //不让回退
      },
      onCancel: () => {},
    });
  };
  componentDidMount() {
    this.getTime();
    this.getWeather();
  }
  render() {
    const { currentTime, dayPictureUrl, weather } = this.state;
    const user = memoryUtils.user.username;
    const title = this.getTitle();
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎, {user}</span>
          <LinkButton onClick={this.logoOut}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <img
              src={
                dayPictureUrl ||
                "http://api.map.baidu.com/images/weather/day/qing.png"
              }
              title="天气"
              alt=""
            />
            <span>{weather || "晴"}</span>
          </div>
        </div>
      </div>
    );
  }
}

export default withRouter(Header);
